package com.zbcn.combootjdbctemplate.controller;

import com.zbcn.combootjdbctemplate.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class JdbcTemplateController {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@GetMapping
	public List<User> queryUsers(){

		String sql = "select * from t_user";
		return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));
	}

	@GetMapping("/{id}")
	public User getUser(@PathVariable Long id){

		String sql = "select * from t_user where id = ?";
		return jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper<>(User.class));
	}

	@DeleteMapping("/{id}")
	public int delUser(@PathVariable Long id){
		String sql = "delete from t_user where id = ?";
		return jdbcTemplate.update(sql,id);
	}

	@PostMapping
	public int addUser(@RequestBody User user){
		String sql ="insert into t_user(username, password) values(?, ?)";
		return jdbcTemplate.update(sql,user.getUsername(),user.getPassword());
	}

	@PutMapping("/{id}")
	public int editUser(@PathVariable Long id, @RequestBody User user) {
		// 根据主键ID修改用户信息
		String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?";
		return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id);
	}
}
